package com.tnovoselec.android.common.ui.splash;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MotionEvent;

/**
 * Title: Framework <br />
 * Copyright: Copyright (c) 2011 <br />
 * 
 * The SplashScreen is used to easily show splash screen. (Full screen image
 * which is shown for defined ammount of time)
 * 
 * @author Tomislav Novoselec
 * @version 1.0.0
 * @since 1.0.0
 */
public abstract class SplashScreen extends Activity {

    /**
     * 
     * @return id of layout which will be shown as splash
     */
    public abstract int getContentViewId();

    /**
     * 
     * @return duration of splash screen in millis
     */
    public abstract long getDuration();

    /**
     * 
     * @return class (Activity) which will be started after splash screen is
     *         over
     */
    public abstract Class<? extends Activity> getIntentClass();

    private Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	super.setContentView(getContentViewId());

	handler.postDelayed(run, SplashScreen.this.getDuration());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	super.onCreateOptionsMenu(menu);
	return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
	if (event.getAction() == MotionEvent.ACTION_DOWN) {
	    handler.removeCallbacks(run);
	    runOnUiThread(run);
	}

	return true;
    }

    private Runnable run = new Runnable() {

	private boolean finished = false;

	@Override
	public void run() {

	    synchronized (this) {
		if (finished) {
		    return;
		}

		Intent intent = new Intent();
		intent.setClass(SplashScreen.this, SplashScreen.this.getIntentClass());
		SplashScreen.this.startActivity(intent);
		SplashScreen.this.finish();

		finished = true;
	    }
	}
    };

}
